/*
 * This is Melet, a salary slip designer. Feed it with data regarding to salary payment, prepare it for print through the graphical presentation, and you have it done.
 * Copyright (C) 2014, AFDiaX
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This program is based on UMLet, a Free UML Tool for Fast UML Diagrams.
 * To contact the authors of UMLet visit https://code.google.com/p/umlet/people/list
 * To contact the authors of Melet visit https://gna.org/users/gabocze
 */
package com.baselet.generator.java.bcel;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.log4j.Logger;

public class BcelJavaClass implements com.baselet.generator.java.JavaClass {

	private static final Logger log = Logger.getLogger(BcelJavaClass.class);

	private JavaClass clazz;
	private String className;

	public BcelJavaClass(String filename) {
		try {
			ClassParser parser = new ClassParser(filename);
			clazz = parser.parse();
		} catch (Exception e) {
			log.error("BCEL library failed to parse " + filename, e);
		}
	}

	@Override
	public String getName() {
		String nameWithPackage = clazz.getClassName();
		className = nameWithPackage.substring(nameWithPackage.lastIndexOf(".") + 1, nameWithPackage.length());
		return className;
	}

	@Override
	public com.baselet.generator.java.Field[] getFields() {
		Field[] fields = clazz.getFields();
		BcelField[] newFields = new BcelField[fields.length];
		for (int i = 0; i < fields.length; ++i) {
			newFields[i] = new BcelField(fields[i]);
		}
		return newFields;
	}

	@Override
	public com.baselet.generator.java.Method[] getMethods() {
		Method[] methods = clazz.getMethods();
		BcelMethod[] newMethods = new BcelMethod[methods.length];
		for (int i = 0; i < methods.length; ++i) {
			newMethods[i] = new BcelMethod(methods[i], className);
		}
		return newMethods;
	}

	@Override
	public ClassRole getRole() {
		if (clazz.isInterface()) {
			return ClassRole.INTERFACE;
		}
		else if (clazz.isAbstract()) {
			return ClassRole.ABSTRACT;
		}
		else {
			return ClassRole.CLASS;
		}
	}

	@Override
	public String getPackage() {
		return clazz.getPackageName();
	}
}
